﻿using System;
using System.IO;
using System.Linq;
using Microsoft.Win32;

namespace Microsoft.WowAddonStudio.Setup.CustomActions
{
    public static class WowManager
    {
        private const string wowPathSubKeyName = @"SOFTWARE\Blizzard Entertainment\World of Warcraft";
        private const string wowPathName = "InstallPath";

        private const string mpqDataFolder = "Data";
        private const string localizedMpqPathFormat = "Data/{1}/{0}-{1}.mpq";

        /// <summary>
        /// Gets a value indicating whether World of Warcraft is installed.
        /// </summary>
        public static bool IsWowInstalled
        {
            get { return WowManager.GetWowPath() != null; }
        }

        /// <summary>
        /// Gets the installed locales in World of Warcraft.
        /// </summary>
        /// <returns></returns>
        public static string[] GetLocales()
        {
            if (!IsWowInstalled)
                throw new InvalidOperationException("World of Warcraft is not installed.");

            string wowPath = WowManager.GetWowPath();

            if (wowPath != null)
            {
                string dataPath = Path.Combine(wowPath, mpqDataFolder);
                if (Directory.Exists(dataPath))
                    return
                        Directory.GetDirectories(dataPath).Select(
                            directory => directory.Substring(directory.LastIndexOf(Path.DirectorySeparatorChar) + 1)).
                            ToArray();
            }

            return null;
        }

        public static string GetLocalizedMpqPath(string mpqBaseName, string locale)
        {
            if (mpqBaseName == null)
                throw new ArgumentNullException("mpqBaseName");
            if (mpqBaseName == null)
                throw new ArgumentNullException("mpqBaseName");

            return String.Format(localizedMpqPathFormat, mpqBaseName, locale);
        }

        public static string GetWowPath()
        {
            using (RegistryKey key = Registry.LocalMachine.OpenSubKey(wowPathSubKeyName))
            {
                if (key != null)
                    return (string) key.GetValue(wowPathName, null);
            }

            return null;
        }
    }
}